package com.director.core;

import com.director.core.json.JsonParser;

import java.lang.reflect.InvocationTargetException;

/**
 * Simple executor adapter that instantiate each time a newly Action object and invoke a method via reflection.
 *
 * @author Simone Ricciardi
 * @version 1.0, 03/06/2011
 */
public class SimpleExecutorAdapter implements ExecutorAdapter {

   public DirectTransactionResult execute(DirectAction directAction, DirectMethod directMethod, DirectTransactionData data) throws DirectException {
      try {
         Class actionClass = directAction.getActionClass();
         Object result = directMethod.getMethod().invoke(actionClass.newInstance(), directMethod.parseParameters(data));
         JsonParser parser = DirectContext.get().getConfiguration().getParser();
         return parser.buildResult(directMethod, result);
      } catch(InvocationTargetException e) {
         String message = "Cannot invoke the action method " + directMethod + " of the direct class " + directAction;
         throw new DirectException(message, e.getTargetException());
      } catch(Throwable e) {
         String message = "Cannot invoke the action method " + directMethod + " of the direct class " + directAction;
         throw new DirectException(message, e);
      }
   }

}
